package ltd.newbee.mall.socket;

import com.corundumstudio.socketio.*;
import com.corundumstudio.socketio.annotation.OnConnect;
import com.corundumstudio.socketio.annotation.OnDisconnect;
import com.corundumstudio.socketio.annotation.OnEvent;
import lombok.extern.slf4j.Slf4j;
import ltd.newbee.mall.common.MessageTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @description:
 * @author: qzx
 * @date: 2022-08-12 17:11
 * @version: 1.0
 */
@Component
@Slf4j
public class SocketConnection {

    @Resource
    private SocketIOServer socketIOServer;

    /**
     * 客户端连接的时候触发
     *
     * @param client SocketIOClient
     */
    @OnConnect
    public void onConnect(SocketIOClient client) {
        log.info("已经链接上客户端 sessionId = {}", client.getSessionId());
        String userId = client.getHandshakeData().getSingleUrlParam("userId");
        log.info("当前用户 userId = {}", userId);
        socketIOServer.getAllClients().stream().filter(cl -> cl.getSessionId().equals(client.getSessionId())).forEach(c -> {
            log.info("====开始发送数据=== sessionId = {}", c.getSessionId());
            c.sendEvent("success", new MessageTemplate("server-->apk"));
        });
        client.sendEvent("success", new VoidAckCallback() {
            @Override
            protected void onSuccess() {
                log.info("====onSuccess===");
            }
        }, new MessageTemplate("AckCallback"));
        client.sendEvent("success", new MessageTemplate("client-->ips"));
    }

    /***
     *  客户端发送过来信息
     * @param client
     * @param request
     * @param template
     */
    @OnEvent("client_send")
    public void onEvent(SocketIOClient client, AckRequest request, MessageTemplate template) {
        log.info("客户端发送过来信息 template = {} ", template);
        client.sendEvent("send_msg", new MessageTemplate("已经收到客户端数据"));
    }

    /**
     * 客户端关闭连接时触发
     *
     * @param client SocketIOClient
     */
    @OnDisconnect
    public void onDisconnect(SocketIOClient client) {
        String userId = client.getHandshakeData().getSingleUrlParam("userId");
        log.info("当前离开用户 userId = {}", userId);
        client.disconnect();
    }

    public void pushMessage(String userId, Object msg) {
        this.pushMessage("send_user", userId, msg);
    }

    public void pushMessage(String eventName, String userId, Object msg) {
        socketIOServer.getAllClients().stream().filter(client -> client.getHandshakeData().getSingleUrlParam("userId").equals(userId)).forEach(client -> {
            if (client.isChannelOpen()) {
                client.sendEvent(eventName, msg);
            }
        });
    }

}
